package com.lijianpo.util.extension.datamasking.util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @author zhangyang
 * @Date 2021/11/24 10:36
 */
public class AesUtil {

    private static final String KEY_AES = "AES";

    private static final String SOURCE_KEY = "good.luculent.cn";


    /**
     * 加密
     * @param str
     * @return
     * @throws Exception
     */
    public static String encrypt(String str)  {

        try{
            byte[] raw = SOURCE_KEY.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, KEY_AES);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(str.getBytes(StandardCharsets.UTF_8));
            Base64.Encoder encoder = Base64.getEncoder();
            return  encoder.encodeToString(encrypted);
        }catch (Exception e){
            return null;
        }
    }

    /**
     * 解密
     * @param str
     * @return
     * @throws Exception
     */
    public static String decrypt(String str)  {
        try {

            byte[] raw = SOURCE_KEY.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, KEY_AES);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            Base64.Decoder decoder = Base64.getDecoder();
            byte[] encrypted1 = decoder.decode(str);
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original,StandardCharsets.UTF_8);
            return originalString;
        } catch (Exception ex) {
            return null;
        }
    }
}
